//
//  Config.m
//  Staff
//
//  Created by caiyao on 11/17/14.
//
//

#import "Config.h"
#import "WebResource.h"
#import "ARResource.h"

@implementation Config

+ (Config *)parserConfigObjectWithJson:(NSDictionary *)jsonDic {
    NSMutableArray *webResources = [[NSMutableArray alloc] init];
    Config *config = [[Config alloc] init];
    if ([[jsonDic objectForKey:@"webresources"] isKindOfClass:[NSDictionary class]]) {
        WebResource *resource = [WebResource parserWebRourceObjectWithJson:[jsonDic objectForKey:@"webresources"]];
        [webResources addObject:resource];
    } else if ([[jsonDic objectForKey:@"webresources"] isKindOfClass:[NSArray class]]) {
        for (NSDictionary *resDic in [jsonDic objectForKey:@"webresources"]) {
            WebResource *resource = [WebResource parserWebRourceObjectWithJson:resDic];
            [webResources addObject:resource];
        }
    }
    config.webResources = [NSMutableArray arrayWithArray:webResources];
    config.configUpdatePeriodInHours = [[jsonDic objectForKey:@"ConfigUpdatePeriod"] intValue];
    config.appVersion = [jsonDic objectForKey:@"Version"];
    config.appUpgradeLink = [jsonDic objectForKey:@"AppUpgradeLink"];
    if ([[jsonDic objectForKey:@"AR"] count]>0) {
        config.arResource = [ARResource parserARResourcWithJson:[[jsonDic objectForKey:@"AR"] objectAtIndex:0]];
    }
    config.isStandaloneMode = YES;
    config.gsrURL = [jsonDic objectForKey:@"GSRURL"];
    config.dashboardAppSchema = [jsonDic objectForKey:@"DashboardsAppSchema"];
    config.dashboardAppStoreURL = [jsonDic objectForKey:@"DashboardsAppStoreLink"];
    return config;
}

- (id) initWithCoder: (NSCoder *)coder
{
    if (self = [super init])
    {
        NSMutableArray *tempArray = [[NSMutableArray alloc] init];
        for (NSData *webr in [coder decodeObjectForKey:@"webResources"]) {
            WebResource *wb = [NSKeyedUnarchiver unarchiveObjectWithData:webr];
            [tempArray addObject:wb];
        }
        self.webResources = [NSArray arrayWithArray:tempArray];
    }
    return self;
}
- (void) encodeWithCoder: (NSCoder *)coder
{
    NSMutableArray *tempArray = [[NSMutableArray alloc] init];
    for (WebResource *webResource in _webResources) {
        [tempArray addObject:[NSKeyedArchiver archivedDataWithRootObject:webResource]];
    }
    [coder encodeObject:tempArray forKey:@"webResources"];
}

@end
